#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()

import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5
import requests, json, time, base64
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256

from equity_mall.utils.utils import random_str
from vouchers.models import AliDiscountCoupon, AliDiscountCouponMerchant
from merchants.models import MerchantChannel


def rsa_long_encrypt(message, pub_key):
    rsakey = RSA.importKey(pub_key)
    cipher = sign_PKCS1_v1_5.new(rsakey)
    rand_hash = SHA256.new()
    rand_hash.update(message.encode())
    signature = cipher.sign(rand_hash)
    return str((base64.b64encode(signature)), encoding="utf-8")


def sync_activity_merchant():
    queryset = AliDiscountCoupon.objects.filter(coupon_channel=2)
    for query in queryset:
        pub_key = query.platform.pub_key
        mchid = query.platform.mchid
        serial_no = query.platform.serial_no
        offset = 0
        while True:
            UFDODER_URL = f'https://api.mch.weixin.qq.com/v3/marketing/favor/stocks/{query.template_id}/merchants?offset={offset}&limit=50&stock_creator_mchid={mchid}'
            nonce_str = random_str()
            timestamp = int(time.time())
            message = f'GET\n/v3/marketing/favor/stocks/{query.template_id}/merchants?offset={offset}&limit=50&stock_creator_mchid={mchid}\n{timestamp}\n{nonce_str}\n\n'
            signature = rsa_long_encrypt(message, pub_key)
            headers = {
                'Authorization': f'WECHATPAY2-SHA256-RSA2048 mchid="{mchid}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{serial_no}"'}
            response = requests.request('get', UFDODER_URL, headers=headers)
            dict_data = json.loads(response.content)
            print(dict_data)
            print(query.template_id)
            if 'data' not in dict_data:
                break
            offset += 1
            sub_mchid_list = dict_data['data']
            for sub_mchid in sub_mchid_list:
                alidiscountcouponmerchant_data = {}
                alidiscountcouponmerchant_data['alidiscountcoupon_id'] = query.id
                alidiscountcouponmerchant_data['sub_mchid'] = sub_mchid
                merchant = MerchantChannel.objects.filter(sub_mchid=sub_mchid).first()
                if merchant:
                    alidiscountcouponmerchant_data['merchant_id'] = merchant.merchant_id
                AliDiscountCouponMerchant.objects.get_or_create(
                    defaults=alidiscountcouponmerchant_data,
                    sub_mchid=sub_mchid,
                    alidiscountcoupon_id=query.id
                )


def wash_sub_mchid():
    query_set = AliDiscountCouponMerchant.objects.filter(channel_id__isnull=True)
    for query in query_set:
        merchant = MerchantChannel.objects.filter(sub_mchid=query.sub_mchid).first()
        if merchant:
            query.channel_id = merchant.channel_id
            query.save()


if __name__ == '__main__':
    wash_sub_mchid()